package com.suzhe.ymall.order.listener;

import com.suzhe.ymall.common.enums.MessageRoleEnum;
import com.suzhe.ymall.common.enums.TopicEnum;
import com.suzhe.ymall.common.message.PaySuccessMessage;
import com.suzhe.ymall.common.utils.YMJsonUtils;
import com.suzhe.ymall.order.pojo.MessageLog;
import com.suzhe.ymall.order.service.IMessageLogService;
import com.suzhe.ymall.order.service.IOrderService;
import com.suzhe.ymall.order.service.IOrderStatusService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author suzhe
 * @date 2019/8/13
 */
@Slf4j
@Component
// topic需要和生产者的topic一致，consumerGroup属性是必须指定的，内容可以随意
@RocketMQMessageListener(topic = "PAY_SUCCESS", consumerGroup = "order-pay-success")
public class PaySuccessListener implements RocketMQListener<PaySuccessMessage> {

    @Autowired
    IOrderStatusService iOrderStatusService;

    @Autowired
    IOrderService iOrderService;

    @Autowired
    IMessageLogService iMessageLogService;

    /**
     * 监听到消息的时候就会调用该方法
     *
     * @param message 消息
     */
    @Override
    public void onMessage(PaySuccessMessage message) {
        log.info("PAY_SUCCESS receive msg：{}", message);
        String messageId = message.getMessageId();
        MessageLog messageLog = iMessageLogService.getById(messageId);
        if (messageLog == null){
            //持久化到本地消息日志表
            messageLog = new MessageLog();
            messageLog.setId(messageId);
            messageLog.setMessageRole(MessageRoleEnum.RECEIVER.value());
            messageLog.setMessageTopic(TopicEnum.PAY_SUCCESS.value());
            messageLog.setMessageBody(YMJsonUtils.toJson(message));
            iMessageLogService.save(messageLog);
            //异步处理
            iOrderService.paySuccess(messageId,message.getOrderNo());
        }

    }
}
